var baseUrl = $(".baseUrl").text();
var map;


function initialize() {
  var mapOptions = {
    zoom: 12 
  }


        
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  
// Try HTML5 geolocation
if(navigator.geolocation) {
   
    navigator.geolocation.getCurrentPosition(function(position) {

        var populationOptions = {
                strokeColor: '#FF0000',
                strokeOpacity: 0.8,
                strokeWeight: 1.5,
                fillColor: '#FF0000',
                fillOpacity: 0.2,
                map: map,
                center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
                radius: 3000 /* 3000 km */
        };
          // Add the circle for this city to the map.
          new google.maps.Circle(populationOptions);

      map.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
      
    }, function() {
      handleNoGeolocation(true);
    });
  } else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
}


  var image = {
    url: baseUrl+'/public/img/marker.png',

  };

  var shape = {
      coords: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  
    $.getJSON(baseUrl+'/mercado/ajax-buscar-coordenadas',
        function(j){
            $(j).each(function(i){
                var myLatLng = new google.maps.LatLng(this[1], this[2]);
                var marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    icon: image,
                    shape: shape,
                    title: this[0],
                    zIndex: this[3]
                });
            });
        });  
}

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: O servi&ccedil;o Geolocaliza&ccedil;&atilde;ode falhou.';
  } else {
    var content = 'Error: O navegador n&atilde;o suporta Geolocaliza&ccedil;&atilde;o.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(-22.898315747797405,-43.369903564453125),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}

google.maps.event.addDomListener(window, 'load', initialize);

